# 用户画像API端点
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import Dict, Any, Optional
from app.configs.database import get_db
from app.models import User
from app.services.conversation_service import ConversationService
from app.api.endpoints.auth import get_current_user
import logging

logger = logging.getLogger(__name__)
router = APIRouter()


def _calculate_stability_score(emotion_history: list) -> int:
    """计算情绪稳定性评分 (1-10)"""
    if not emotion_history or len(emotion_history) < 2:
        return 5  # 默认中等稳定性

    # 计算情绪变化次数
    changes = 0
    for i in range(1, len(emotion_history)):
        if emotion_history[i].get('emotion') != emotion_history[i-1].get('emotion'):
            changes += 1

    # 计算稳定性评分（变化越少越稳定）
    change_rate = changes / len(emotion_history)
    if change_rate < 0.2:
        return 9  # 非常稳定
    elif change_rate < 0.4:
        return 7  # 较稳定
    elif change_rate < 0.6:
        return 5  # 中等稳定
    elif change_rate < 0.8:
        return 3  # 较不稳定
    else:
        return 1  # 很不稳定


def _generate_emotion_recommendations(overall_mood: str, stability_score: int, emotion_history: list) -> list:
    """根据情绪状态生成建议"""
    recommendations = []

    # 基于整体情绪的建议
    if overall_mood in ['sad', 'depressed']:
        recommendations.extend([
            "建议寻求专业心理咨询师的帮助",
            "尝试与信任的朋友或家人分享您的感受",
            "考虑进行适量的户外运动，如散步或慢跑",
            "保持规律的作息时间，确保充足的睡眠"
        ])
    elif overall_mood in ['anxious', 'stressed']:
        recommendations.extend([
            "尝试深呼吸练习或冥想来缓解焦虑",
            "制定合理的日程安排，避免过度压力",
            "考虑学习一些放松技巧，如渐进性肌肉放松",
            "适当减少咖啡因摄入，避免加重焦虑"
        ])
    elif overall_mood == 'angry':
        recommendations.extend([
            "尝试通过运动来释放负面情绪",
            "学习愤怒管理技巧，如暂停和冷静",
            "考虑写日记来表达和处理愤怒情绪",
            "寻找健康的情绪表达方式"
        ])
    elif overall_mood == 'happy':
        recommendations.extend([
            "继续保持积极的生活态度",
            "分享您的快乐，帮助他人也感受正能量",
            "记录美好时刻，建立积极的回忆库",
            "保持当前的健康生活习惯"
        ])
    else:  # neutral
        recommendations.extend([
            "尝试探索新的兴趣爱好来丰富生活",
            "建立规律的运动习惯来提升整体健康",
            "培养感恩的心态，关注生活中的美好",
            "与朋友和家人保持良好的社交联系"
        ])

    # 基于稳定性的建议
    if stability_score < 4:
        recommendations.append("您的情绪波动较大，建议寻求专业帮助来学习情绪调节技巧")
    elif stability_score > 7:
        recommendations.append("您的情绪状态相对稳定，继续保持良好的心理健康习惯")

    return recommendations[:4]  # 限制建议数量

@router.get("/emotion-profile")
async def get_user_emotion_profile(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
) -> Dict[str, Any]:
    """获取当前用户的情绪画像"""
    try:
        logger.info(f"[UserProfile] 获取用户情绪画像: user_id={current_user.user_id}")

        conversation_service = ConversationService(db)
        emotion_profile = conversation_service.get_user_emotion_profile(str(current_user.user_id))

        if not emotion_profile or not emotion_profile.get('emotion_history'):
            # 返回前端期望的格式，但使用模拟数据
            return {
                "user_id": str(current_user.user_id),
                "current_emotion": None,
                "emotion_updated_at": None,
                "emotion_history": [],
                "emotion_history_count": 0,
                # 前端期望的格式
                "primary_emotions": [
                    {"emotion": "neutral", "percentage": 100}
                ],
                "overall_mood": "neutral",
                "stability_score": 5,
                "recommendations": [
                    "开始与我对话，我将分析您的情绪状态",
                    "分享您的感受和想法，帮助我更好地了解您"
                ],
                "message": "用户情绪画像暂无数据，请开始对话以建立情绪档案"
            }

        # 处理情绪历史数据，转换为前端期望的格式
        emotion_history = emotion_profile.get('emotion_history', [])

        # 统计情绪分布
        emotion_counts = {}
        total_records = len(emotion_history)

        for record in emotion_history:
            emotion = record.get('emotion', 'neutral')
            emotion_counts[emotion] = emotion_counts.get(emotion, 0) + 1

        # 计算情绪百分比
        primary_emotions = []
        for emotion, count in emotion_counts.items():
            percentage = round((count / total_records) * 100, 1) if total_records > 0 else 0
            primary_emotions.append({
                "emotion": emotion,
                "percentage": percentage
            })

        # 按百分比排序
        primary_emotions.sort(key=lambda x: x['percentage'], reverse=True)

        # 确定整体情绪
        overall_mood = primary_emotions[0]['emotion'] if primary_emotions else 'neutral'

        # 计算稳定性评分（基于情绪变化频率）
        stability_score = _calculate_stability_score(emotion_history)

        # 生成建议
        recommendations = _generate_emotion_recommendations(overall_mood, stability_score, emotion_history)

        result = {
            "user_id": str(current_user.user_id),
            "current_emotion": emotion_profile.get('current_emotion'),
            "emotion_updated_at": emotion_profile.get('emotion_updated_at'),
            "emotion_history": emotion_history,
            "emotion_history_count": total_records,
            # 前端期望的格式
            "primary_emotions": primary_emotions,
            "overall_mood": overall_mood,
            "stability_score": stability_score,
            "recommendations": recommendations
        }

        logger.info(f"[UserProfile] 情绪画像获取成功: user_id={current_user.user_id}, current_emotion={emotion_profile.get('current_emotion')}, total_records={total_records}")
        return result
        
    except Exception as e:
        logger.error(f"[UserProfile] 获取用户情绪画像失败: user_id={current_user.user_id}, error={e}")
        raise HTTPException(
            status_code=500,
            detail=f"获取用户情绪画像失败: {str(e)}"
        )

@router.get("/emotion-stats")
async def get_user_emotion_stats(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
) -> Dict[str, Any]:
    """获取用户情绪统计信息"""
    try:
        logger.info(f"[UserProfile] 获取用户情绪统计: user_id={current_user.user_id}")
        
        conversation_service = ConversationService(db)
        emotion_profile = conversation_service.get_user_emotion_profile(str(current_user.user_id))
        
        if not emotion_profile or not emotion_profile.get('emotion_history'):
            return {
                "user_id": str(current_user.user_id),
                "total_records": 0,
                "emotion_distribution": {},
                "recent_emotions": [],
                "message": "暂无情绪数据"
            }
        
        emotion_history = emotion_profile['emotion_history']
        
        # 统计情绪分布
        emotion_distribution = {}
        for record in emotion_history:
            emotion = record.get('emotion', 'unknown')
            emotion_distribution[emotion] = emotion_distribution.get(emotion, 0) + 1
        
        # 获取最近10条情绪记录
        recent_emotions = emotion_history[-10:] if len(emotion_history) > 10 else emotion_history
        
        stats = {
            "user_id": str(current_user.user_id),
            "total_records": len(emotion_history),
            "emotion_distribution": emotion_distribution,
            "recent_emotions": recent_emotions,
            "current_emotion": emotion_profile.get('current_emotion'),
            "last_updated": emotion_profile.get('emotion_updated_at')
        }
        
        logger.info(f"[UserProfile] 情绪统计获取成功: user_id={current_user.user_id}, total_records={len(emotion_history)}")
        return stats
        
    except Exception as e:
        logger.error(f"[UserProfile] 获取用户情绪统计失败: user_id={current_user.user_id}, error={e}")
        raise HTTPException(
            status_code=500,
            detail=f"获取用户情绪统计失败: {str(e)}"
        )

@router.delete("/emotion-profile")
async def clear_user_emotion_profile(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
) -> Dict[str, Any]:
    """清空用户情绪画像数据"""
    try:
        logger.info(f"[UserProfile] 清空用户情绪画像: user_id={current_user.user_id}")
        
        # 直接更新用户的情绪相关字段
        user = db.query(User).filter(User.user_id == str(current_user.user_id)).first()
        if not user:
            raise HTTPException(status_code=404, detail="用户不存在")
        
        user.current_emotion = None
        user.emotion_history = None
        user.emotion_updated_at = None
        
        db.commit()
        
        logger.info(f"[UserProfile] 用户情绪画像清空成功: user_id={current_user.user_id}")
        return {
            "message": "用户情绪画像已清空",
            "user_id": str(current_user.user_id)
        }
        
    except Exception as e:
        logger.error(f"[UserProfile] 清空用户情绪画像失败: user_id={current_user.user_id}, error={e}")
        db.rollback()
        raise HTTPException(
            status_code=500,
            detail=f"清空用户情绪画像失败: {str(e)}"
        )